<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 采购申请管理
 *
 * @icon fa fa-shopping-cart
 * @remark 管理缺货物料的采购申请
 */
class PurchaseRequest extends Backend
{
    /**
     * PurchaseRequest模型对象
     * @var \app\admin\model\scanwork\PurchaseRequest
     */
    protected $model = null;
    
    /**
     * 是否开启数据限制
     * @var bool
     */
    protected $dataLimit = false;
    
    /**
     * 是否开启模型验证
     * @var bool
     */
    protected $modelValidate = false;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\PurchaseRequest;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("priorityList", $this->model->getPriorityList());
    }

    /**
     * 查看
     */
    public function index()
    {
        \think\Log::info('PurchaseRequest index方法被调用 - 请求方法: ' . $this->request->method());
        \think\Log::info('PurchaseRequest index方法被调用 - 是否AJAX: ' . ($this->request->isAjax() ? '是' : '否'));
        
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['material', 'supplier'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            
            \think\Log::info('PurchaseRequest index返回数据: ' . json_encode($result));

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 调试信息
                \think\Log::info("采购申请add - 提交的参数: " . json_encode($params));
                
                // 验证必需字段
                if (empty($params['material_id']) || empty($params['supplier_id']) || empty($params['request_quantity'])) {
                    return json(['code' => 0, 'msg' => '请填写完整的物料、供应商和数量信息', 'data' => []]);
                }
                
                // 设置默认值
                $params['request_user_id'] = $this->auth->id;
                $params['request_time'] = time();
                $params['status'] = 1; // 待审核
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                return json(['code' => 0, 'msg' => '参数不能为空', 'data' => []]);
            }
        }
        
        // 获取物料列表
        $materials = \app\admin\model\scanwork\Material::where('status', 1)->select();
        $this->view->assign('materials', $materials);
        
        // 获取供应商列表
        $suppliers = \app\admin\model\scanwork\Supplier::where('status', 1)->select();
        $this->view->assign('suppliers', $suppliers);
        
        return $this->view->fetch();
    }

    /**
     * 从缺货物料生成采购申请（重定向到缺货物料列表）
     */
    public function generateFromShortage()
    {
        return redirect('scanwork/purchase_request/shortage');
    }

    /**
     * 缺货物料列表
     */
    public function shortage()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            // 获取缺货物料
            $list = \app\admin\model\scanwork\Material::where(function($query) {
                $query->where('stock', '<=', 0)
                      ->whereOr('stock', '<', \think\Db::raw('min_stock'));
            })
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        
        return $this->view->fetch();
    }

    /**
     * 创建采购申请对话框
     */
    public function createRequestDialog()
    {
        \think\Log::info("createRequestDialog方法被调用 - 请求方法: " . $this->request->method());
        \think\Log::info("createRequestDialog方法被调用 - POST数据: " . json_encode($this->request->post()));
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 调试信息
                \think\Log::info("采购申请createRequestDialog - 提交的参数: " . json_encode($params));
                
                // 验证必需字段
                if (empty($params['material_id']) || empty($params['supplier_id']) || empty($params['request_quantity'])) {
                    $this->error('请填写完整的物料、供应商和数量信息');
                }
                
                // 设置默认值
                $params['request_user_id'] = $this->auth->id;
                $params['request_time'] = time();
                $params['status'] = 1; // 待审核
                
                // 获取物料价格信息
                $material = \app\admin\model\scanwork\Material::find($params['material_id']);
                if ($material) {
                    // 优先使用物料供应商报价表中的价格
                    $supplierPrice = \app\admin\model\scanwork\MaterialSupplier::where('material_id', $params['material_id'])
                        ->where('supplier_id', $params['supplier_id'])
                        ->where('status', 1)
                        ->find();
                    
                    if ($supplierPrice) {
                        $params['actual_price'] = $supplierPrice->price;
                    } else {
                        // 如果没有供应商报价，使用物料的当前参考价
                        $params['actual_price'] = $material->current_price;
                    }
                }
                
                $result = false;
                Db::startTrans();
                try {
                    \think\Log::info("开始保存采购申请数据: " . json_encode($params));
                    $result = $this->model->allowField(true)->save($params);
                    \think\Log::info("采购申请保存结果: " . ($result ? '成功' : '失败'));
                    
                    if (!$result) {
                        throw new Exception('采购申请保存失败');
                    }
                    
                    Db::commit();
                    \think\Log::info("数据库事务提交成功");
                    
                    // 返回标准JSON格式
                    return json(['code' => 1, 'msg' => '采购申请创建成功', 'data' => ['id' => $this->model->id]]);
                } catch (Exception $e) {
                    Db::rollback();
                    \think\Log::error("采购申请保存异常: " . $e->getMessage());
                    return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => []]);
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        
        // 获取物料ID（单个或多个）
        $materialId = $this->request->get('material_id');
        $materialIds = $this->request->get('material_ids');
        
        \think\Log::info("采购申请对话框 - material_id: " . $materialId);
        \think\Log::info("采购申请对话框 - material_ids: " . json_encode($materialIds));
        
        // 获取物料信息
        if ($materialId) {
            $material = \app\admin\model\scanwork\Material::with('category')->find($materialId);
            $this->view->assign('material', $material);
            $this->view->assign('suggestedQty', max($material->min_stock * 2, 100));
        } else {
            // 如果没有指定物料，显示所有缺货物料供选择
            $materials = \app\admin\model\scanwork\Material::where(function($query) {
                $query->where('stock', '<=', 0)->whereOr('stock', '<', \think\Db::raw('min_stock'));
            })->select();
            $this->view->assign('materials', $materials);
        }
        
        // 获取供应商列表
        $suppliers = \app\admin\model\scanwork\Supplier::where('status', 1)->select();
        $this->view->assign('suppliers', $suppliers);
        
        return $this->view->fetch();
    }

    /**
     * 审核采购申请
     */
    public function approve($ids = null)
    {
        \think\Log::info("审核方法被调用 - 请求方法: " . $this->request->method());
        \think\Log::info("审核方法被调用 - POST数据: " . json_encode($this->request->post()));
        \think\Log::info("审核方法被调用 - URL参数ids: " . $ids);
        
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        
        $ids = $ids ? $ids : $this->request->post("ids");
        \think\Log::info("审核方法 - 最终ids参数: " . json_encode($ids));
        
        if ($ids) {
            $list = $this->model->where('id', 'in', $ids)->select();
            \think\Log::info("审核方法 - 找到记录数: " . count($list));
            
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    $item->save([
                        'status' => 2, // 已审核
                        'approve_user_id' => $this->auth->id,
                        'approve_time' => time()
                    ]);
                }
                Db::commit();
                \think\Log::info("审核方法 - 数据库事务提交成功");
                
                // 直接输出JSON响应
                header('Content-Type: application/json');
                echo json_encode(['code' => 1, 'msg' => '审核成功', 'data' => ['ids' => $ids]]);
                exit;
            } catch (Exception $e) {
                Db::rollback();
                \think\Log::error("审核方法异常: " . $e->getMessage());
                header('Content-Type: application/json');
                echo json_encode(['code' => 0, 'msg' => $e->getMessage(), 'data' => []]);
                exit;
            }
        } else {
            \think\Log::error("审核方法 - ids参数为空");
            header('Content-Type: application/json');
            echo json_encode(['code' => 0, 'msg' => '参数ids不能为空', 'data' => []]);
            exit;
        }
    }
}
